"""
time: 2024/10/25
title: ThTool
message:
处理TH文件
"""
import os


class ThTool:
    def __init__(self, config_path=None):
        if os.path.isfile("../config/config.th"):
            self.th_path = "../config/config.th"
        elif config_path is not None:
            self.th_path = config_path
        else:
            self.th_path = None

    def read_th(self):
        if self.th_path is None:
            print("ERROR 路径为空")
            return None
        with open(self.th_path, 'r', encoding='utf-8') as f:
            value = f.read()
        return value

    def th_value(self):
        th = self.read_th()
        if th is None:
            return None
        # 分割内容
        data_list = th.split('\n')
        # 剔除信息,合并列表
        value_list = []
        temp = []
        for cell in data_list:
            if "--" == cell[:2]:
                continue
            if '[' == cell[:1]:
                if temp:
                    value_list.append(temp)
                    temp = [cell]
                else:
                    temp.append(cell)
            else:
                temp.append(cell)
        value_list.append(temp)
        return value_list

    def th_json(self):
        th = self.th_value()
        if th is None:
            return None
        # 剔除空数据
        result = {}
        for line in th:
            key = line[0][1:-1].lower()
            result[key] = {}
            for cell in line[1:]:
                if cell == '':
                    continue
                val = cell.split(':')
                k = val[0]
                v = ':'.join(val[1:])
                result[key][k.lower()] = v.strip()
        return result


if __name__ == '__main__':
    p = ThTool().th_json()
    print(p)
